package com.shareware.common.utils

import android.annotation.SuppressLint
import android.os.Build
import android.widget.Toast
import androidx.annotation.StringRes
import com.shareware.common.getContextGlobal
import com.shareware.common.toast.ToastFactory
import com.shareware.common.toast.ToastGravityFactory

/**
 * desc: 功能描述
 * 在Android12以后吐司被限制
 * 1文字吐司设置Gravity无效, 但是允许应用后台显示
 * 2自定义吐司下Gravity有效, 但是不允许应用后台显示
 * email: mobiledeveloper@qq.com
 */

object ToastUtil {

    private var toast: Toast? = null
    private val centerToastFactory by lazy {
        ToastGravityFactory()
    }

    /** 取消吐司显示 */
    fun cancel() {
        toast?.cancel()
    }

    @JvmOverloads
    fun toastCenter(@StringRes msg: Int, longDuration: Boolean = false) {
        if (longDuration) {
            longToast(msg, centerToastFactory)
        } else {
            toast(msg, centerToastFactory)
        }
    }

    @JvmOverloads
    fun toastCenter(msg: CharSequence?, longDuration: Boolean = false) {
        if (longDuration) {
            longToast(msg, centerToastFactory)
        } else {
            toast(msg, centerToastFactory)
        }
    }

    /**
     * 短时间显示的吐司
     * @param msg 吐司内容
     */
    @JvmOverloads
    fun toast(@StringRes msg: Int, factory: ToastFactory? = null) {
        showToast(getContextGlobal().getString(msg), Toast.LENGTH_SHORT, factory)
    }

    /**
     * 短时间显示的吐司
     * @param msg 吐司内容
     */
    @JvmOverloads
    fun toast(msg: CharSequence?, factory: ToastFactory? = null) {
        showToast(msg, Toast.LENGTH_SHORT, factory)
    }

    /**
     * 长时间显示的吐司
     * @param msg 吐司内容
     */
    @JvmOverloads
    fun longToast(@StringRes msg: Int, factory: ToastFactory? = null) {
        longToast(getContextGlobal().getString(msg), factory)
    }

    /**
     * 长时间显示的吐司
     * @param msg 吐司内容
     */
    @JvmOverloads
    fun longToast(msg: CharSequence?, factory: ToastFactory? = null) {
        showToast(msg, Toast.LENGTH_LONG, factory)
    }

    /**
     * 显示吐司
     * @param msg 吐司内容
     * @param duration 吐司显示时长 0 短时间显示 1 长时间显示
     */
    @SuppressLint("ShowToast")
    private fun showToast(msg: CharSequence?, duration: Int, toastFactory: ToastFactory? = null) {
        msg ?: return
        cancel()
        runInMainThread {
            if (toastFactory == null) {
                toast = ToastFactory.onCreate(getContextGlobal(), msg, duration)
                toast?.show()
            } else {
                toast = toastFactory.onCreate(getContextGlobal(), msg, duration)
                if (!appBackground || Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
                    toast?.show()
                }
            }
        }
    }
}